package com.atguigu.j_lock_synchronized;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Resources{
    // 使用synchronized
    public synchronized void SayHello(){
        System.out.println(Thread.currentThread().getName()+"...hello");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 使用lock--tryLock()
    Lock lock = new ReentrantLock();
    public void SayHi(){
        try {
            if(lock.tryLock(3,TimeUnit.SECONDS)){
                try{
                    System.out.println(Thread.currentThread().getName()+"...hi");
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }finally {
                    lock.unlock();
                }
            }else {
                System.out.println(Thread.currentThread().getName()+"抢锁失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Resources resources = new Resources();
        // 使用synchronized
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                resources.SayHello();
            }
        },"t1").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                resources.SayHello();
            }
        },"t2").start();*/

        // 使用lock
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                resources.SayHi();
            }
        }, "t1").start();
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                resources.SayHi();
            }
        }, "t2").start();
    }
}
